import { Repository, Like } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { PaginationDto } from '../dto/pagination.dto';
import { PaginationResult } from '../interface/pagination.interface';

@Injectable()
export class BaseService<T> { //分公共页逻辑
  constructor(protected readonly baseService: Repository<T>) {}

  async paginate(
    query: PaginationDto & Record<string, any>,  // 支持分页 + 模糊查询字段
    fuzzyKeys: (keyof T)[] = [],                 // 指定模糊匹配字段
    exactKeys: (keyof T)[] = [],                  // 指定精确匹配字段
    order={},
  ): Promise<PaginationResult<T>> {
    
    const { page = 1, pageSize = 10 } = query;
    const where: any = {};

    for (const key of fuzzyKeys) {
      if (query[key as string]) {
        where[key] = Like(`%${query[key as string]}%`);
      }
    }

    for (const key of exactKeys) {
      if (query[key as string] !== undefined) {
        where[key] = query[key as string];
      }
    }

    const [list, total] = await this.baseService.findAndCount({
      where,
      skip: (page - 1) * pageSize,
      take: pageSize,
      order
    });

    return {
      list,
      total,
      page,
      pageSize:pageSize,
      totalPages: Math.ceil(total / pageSize)
    };
  }
}